<template>
    <div class="chat-panel">
    <div class="chat-title">心理测评助手</div>
    <div class="message-panel" id="message-panel">
      <div class="message-list">
        <div :class="['message-item',item.type==1?'ai-item':'']" v-for="(item,index) in messageList" :id="'item'+index">
          <template v-if="item.type==0">
            <div class="message-content">
              <div class="content-inner">{{item.content}}</div>
            </div>
            <div class="user-icon">
              我
            </div>
          </template>
          <template v-else>
            <div class="user-icon">
              chat
            </div>
            <div class="message-content ai-item">
              <MdPreview previewTheme="vuepress" :codeFoldable="false" editorId="preview"
                :modelValue="item.content.join('')" />
              <div class="loading" v-if="item.loading">
                <img src="@/assets/loading.gif">
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="send-panel">
      <el-form :model="formData" ref="formDataRef" @submit.prevent>
        <!--input输入-->
        <el-form-item label="" prop="content">
          <el-input type="textarea" :rows="3" clearable placeholder="请输入你想问的问题" v-model="formData.content"
            @keyup="keySend"></el-input>
        </el-form-item>
        <!--input输入-->
        <el-form-item label="" prop="" class="send-btn">
          <el-button type="primary" @click="sendMessage" :disabled="loading">发送(ctrl+enter)</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { ElMessage } from 'element-plus'

import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
} from 'vue'
const { proxy } = getCurrentInstance()
import { MdPreview, MdCatalog } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

const formData = ref({})
const messageList = ref([])
const loading = ref(false)

const keySend = (event) => {
  if (!(event.ctrlKey && event.key === 'Enter')) {
    return
  }
  sendMessage()
}

const prompt = `你是一位资深的心理咨询师，拥有丰富的临床经验和心理学专业知识。你将通过询问用户基本的心理问题，获取用户的问答来分析用户的心理状态进行评估，不要说你是扮演的，你就是，最后给出用户的得分，以及结果描述，`

onMounted(()=>{
  sendMessage();
})

const sendMessage = () => {
  const message = formData.value.content;
  if (!message&&!prompt) {
    ElMessage({
      type: 'warning',
      message: '请输入内容',
      duration: 2000,
    })
    return
  }
  messageList.value.push({
    type: 0,
    content: message,
  })

  messageList.value.push({
    type: 1,
    content: [],
    loading: true,
  })
  loading.value = true
  let eventSource;
  if(message){
    eventSource = new EventSource(`/api/stream?message=${message}`)
  }else{
    eventSource = new EventSource(`/api/stream?message=${prompt}`)
  }

  formData.value.content = ''
  eventSource.onmessage = (event) => {
    let response = event.data
    console.log(response)
    if (response == 'end') {
      close()
      return
    }
    response = JSON.parse(response).content
    messageList.value[messageList.value.length - 1].content.push(response)
    //滚动到底部
    nextTick(() => {
      const content = document.getElementById('message-panel')
      content.scrollTop = content.scrollHeight
    })
    prompt="";
  }

  eventSource.onerror = (error) => {
    close()
  }

  const close = () => {
    eventSource.close()
    messageList.value[messageList.value.length - 1].loading = false
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.chat-panel {
  background: #eff0f6;
  height: calc(100vh - 100px); /* 保持高度不变 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .chat-title {
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      padding: 20px 0; /* 增加一些内边距 */
  }

  .message-panel {
      flex: 1;
      overflow: auto;
      padding: 10px 0;
      background: #fff; /* 背景色改为白色 */
      margin: 0 auto;
      width: 800px;
      border-radius: 10px; /* 增加圆角 */
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 增加阴影效果 */

      .message-list {
          margin: 0 auto;
          width: 90%; /* 调整宽度 */
          .message-item {
              margin: 10px 0;
              display: flex;
              align-items: flex-start;

              .user-icon {
                  width: 40px;
                  height: 40px;
                  line-height: 40px;
                  border-radius: 50%; /* 圆形图标 */
                  background: #535353;
                  color: #fff;
                  text-align: center;
                  margin-right: 10px; /* 调整间距 */
              }

              .message-content {
                  flex: 1;
                  display: flex;
                  align-items: center;
                  justify-content: flex-end;
              }

              .content-inner {
                  background: #2d65f7;
                  border-radius: 10px; /* 增加圆角 */
                  padding: 10px;
                  color: #fff;
                  max-width: 70%; /* 限制消息框宽度 */
              }
          }

          .ai-item {
              .message-content {
                  background: #f5f5f5; /* 浅灰色背景 */
                  border-radius: 10px;
                  padding: 10px;
                  max-width: 70%; /* 限制消息框宽度 */
              }

              .user-icon {
                  background: #64018f;
                  margin-right: 0;
              }

              :deep(.md-editor-previewOnly) {
                  border-radius: 10px;
                  background: #f5f5f5;
              }

              :deep(.md-editor-preview-wrapper) {
                  padding: 10px;
              }

              .loading {
                  text-align: center;
                  padding: 10px;
              }
          }
      }
  }

  .send-panel {
      margin: 10px auto;
      width: 800px;
      background: #fff;
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 增加阴影效果 */

      .send-btn {
          text-align: right;
          margin-bottom: 0;
          padding: 5px;

          :deep(.el-form-item__content) {
              justify-content: flex-end;
          }
      }

      :deep(.el-textarea__inner) {
          border: 0 !important;
          resize: none !important;
          box-shadow: none;
          padding: 10px; /* 增加内边距 */
      }
  }
}

.no-data {
  text-align: center;
  color: #5f5f5f;
  padding: 20px; /* 增加内边距 */
}
</style>
